package com.hmchat.controller.api;

import com.hmchat.model.dto.ApiResponse;
import com.hmchat.model.dto.UserLoginDTO;
import com.hmchat.model.dto.UserRegisterDTO;
import com.hmchat.model.entity.User;
import com.hmchat.repository.UserRepository;
import com.hmchat.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class AuthController {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<Map<String, Object>>> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerDTO.getUsername())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("用户名已存在"));
        }

        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(registerDTO.getEmail())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("邮箱已存在"));
        }

        // 检查手机号是否已存在（如果提供了手机号）
        if (registerDTO.getPhone() != null && !registerDTO.getPhone().isEmpty() 
                && userRepository.existsByPhone(registerDTO.getPhone())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error("手机号已存在"));
        }

        // 创建新用户
        User user = User.builder()
                .username(registerDTO.getUsername())
                .email(registerDTO.getEmail())
                .phone(registerDTO.getPhone())
                .password(passwordEncoder.encode(registerDTO.getPassword()))
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .enabled(true)
                .roles(new String[]{"ROLE_USER"})
                .build();

        User savedUser = userRepository.save(user);

        // 生成JWT令牌
        String token = jwtUtils.generateToken(savedUser);

        // 构建响应数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("user", savedUser);

        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success("注册成功", responseData, token));
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        // 支持多种登录方式查询
        Optional<User> userOptional = userRepository.findByUsernameOrEmailOrPhone(
            loginDTO.getAccount(), 
            loginDTO.getAccount(), 
            loginDTO.getAccount());

        if (userOptional.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("账号不存在"));
        }

        User user = userOptional.get();

        // 添加账户状态检查
        if (!user.isEnabled()) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error("账号已被禁用"));
        }

        // 密码错误次数检查逻辑
        if (user.getFailedAttempts() >= 5) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error("密码错误次数过多，请稍后再试"));
        }

        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            userRepository.incrementFailedAttempts(user.getId());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("密码错误，剩余尝试次数：" + (5 - user.getFailedAttempts())));
        }

        // 重置失败计数
        userRepository.resetFailedAttempts(user.getId());

        // 生成JWT令牌（添加更多声明）
        String token = jwtUtils.generateToken(user);

        // 构建响应数据（过滤敏感字段）
        Map<String, Object> userData = new HashMap<>();
        userData.put("userId", user.getId());
        userData.put("username", user.getUsername());
        userData.put("avatar", user.getAvatar());

        return ResponseEntity.ok()
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
                .body(ApiResponse.success("登录成功", userData, token));
    }
}